package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.ssoAndDoc.utils.Base64Util;
import com.seeyon.apps.ssoAndDoc.utils.HttpUtils;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.content.comment.CommentManager;
import com.seeyon.ctp.common.processlog.manager.ProcessLogManager;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.workflow.manager.ProcessManager;
import com.seeyon.v3x.edoc.manager.EdocManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

@Path("myjsxy")
@Produces({"application/json"})
public class MyjsxyResource
        extends BaseResource
{
    private static final Log log = LogFactory.getLog(MyjsxyResource.class);

    private final OrgManager orgManager =(OrgManager) AppContext.getBean("orgManager");

    private final ColManager colManager = (ColManager) AppContext.getBean("colManager");

    private final EdocManager edocManager =(EdocManager) AppContext.getBean("edocManager");

    private final CommentManager commentManager = (CommentManager) AppContext.getBean("ctpCommentManager");

    private final ProcessManager processManager = (ProcessManager) AppContext.getBean("processManager");

    private final AffairManager affairManager = (AffairManager) AppContext.getBean("affairManager");

    private final ProcessLogManager processLogManager = (ProcessLogManager) AppContext.getBean("processLogManager");




    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @POST
    @Produces({MediaType.APPLICATION_JSON })
    @Path("getRedirectUrl")
    public JSONObject getRedirectUrl(@Context HttpServletRequest request)  {
        JSONObject jsonObject1 = new JSONObject();
        try {
            //访问对方接口
            String yhToken = request.getParameter("yhToken");
            String systemCode = request.getParameter("systemCode");
            String getMemberUrl = "http://192.168.100.186:9600/yhyl/interaction";
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            long messageId = UUIDLong.longUUID();
            String createTime = format.format(date);
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<YHYL MessageId=\""+messageId+"\" Action=\"TYQX_YHXXHQ\" Sender=\"OA\">\n" +
                    "<Message CreateTime=\""+createTime+"\">\n" +
                    "<!-- 子组件一般对应一个单表-->\n" +
                    "<Component Name=\"\" Option=\"find\" PK=\"\">\n" +
                    "<!-- 数据循环最小单位节点-->\n" +
                    "<Entry>\n" +
                    "<Field Name=\"yhToken\" Value=\""+yhToken+"\" Explain=\"token\" Required=\"true\" Len=\"500\"/>\n" +
                    "<Field Name=\"systemCode\" Value=\""+systemCode+"\" Explain=\" 系统code, 系统的唯一id\" Required=\"true\"\n" +
                    "Len=\"100\"/>\n" +
                    "</Entry>\n" +
                    "</Component>\n" +
                    "</Message>\n" +
                    "</YHYL>";
            log.info(".10096:"+xml);
            String result = HttpUtils.sendPost(getMemberUrl,xml);
            log.info("接口返回的数据:"+result);
            // 解析 XML 数据
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new java.io.ByteArrayInputStream(result.getBytes("UTF-8")));

            // 使用 XPath 提取 username 的 Value
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xpath = xPathFactory.newXPath();
            XPathExpression expression = xpath.compile("//Field[@Name='username']/@Value");
            NodeList nodes = (NodeList) expression.evaluate(document, javax.xml.xpath.XPathConstants.NODESET);
            // 输出 username 的 value
            if (nodes.getLength() > 0) {
                String loginName = nodes.item(0).getNodeValue();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("loginName", loginName);
                jsonObject.put("time", System.currentTimeMillis());
                String jsonString = jsonObject.toString();
                String ticket = Base64Util.getBaseString(jsonString.getBytes(StandardCharsets.UTF_8));
                String ticket1 = URLEncoder.encode(ticket, StandardCharsets.UTF_8.toString());
                String ssoLoginUrl;
                ssoLoginUrl = "/seeyon/login/sso?from=myjsxysso&ticket="+ticket1;
                log.info("拼接的url:"+ssoLoginUrl);
                jsonObject1.put("code",200);
                jsonObject1.put("msg","获取成功");
                jsonObject1.put("data",ssoLoginUrl);
                return jsonObject1;
            } else {
                log.error("获取username失败");
                jsonObject1.put("code",500);
                jsonObject1.put("msg","获取失败");
                return jsonObject1;
            }
        }catch (Exception e){
            jsonObject1.put("code",500);
            log.error("跳转失败",e);
            return jsonObject1;
        }
    }
}
